package com.chenjunlin.shortlink.admin.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chenjunlin.shortlink.admin.common.constant.RedisConstant;
import com.chenjunlin.shortlink.admin.common.convention.exception.ClientException;
import com.chenjunlin.shortlink.admin.common.enums.UserErrorCodeEnun;
import com.chenjunlin.shortlink.admin.dao.entity.UserDO;
import com.chenjunlin.shortlink.admin.dao.mapper.UserMapper;
import com.chenjunlin.shortlink.admin.dto.reqtDTO.UserLoginReqDTO;
import com.chenjunlin.shortlink.admin.dto.reqtDTO.UserRegisterReqDTO;
import com.chenjunlin.shortlink.admin.dto.reqtDTO.UserUpdateReqDTO;
import com.chenjunlin.shortlink.admin.dto.resp.UserLoginRespDTO;
import com.chenjunlin.shortlink.admin.dto.resp.UserRespDTO;
import com.chenjunlin.shortlink.admin.service.UserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    private final RBloomFilter rBloomFilter;
    private final RedissonClient redissonClient;
    private final RedisTemplate redisTemplate;

    @Override
    public UserRespDTO getUserByUsername(String username) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, username)
                .eq(UserDO::getDelFlag, 0);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if(userDO == null){
            throw new ClientException(UserErrorCodeEnun.USER_NOT_FIND);
        }
        UserRespDTO userRespDTO = new UserRespDTO();
        BeanUtils.copyProperties(userDO,userRespDTO);
        return userRespDTO;
    }


    /**
     * 判断用户名是否可用(重复)
     * @param username
     * @return 用户名可用的时候返回True
     */
    @Override
    public Boolean validUsername(String username) {
        return !rBloomFilter.contains(username);
    }

    @Override
    public void register(UserRegisterReqDTO userRegisterReqDTO) {
        //1.首先判断用户名是否已经存在
        if(!validUsername(userRegisterReqDTO.getUsername())){
            //如果用户名已经存在 则抛出异常 结束
            throw new ClientException(UserErrorCodeEnun.USER_ALREADY_EXIST);
        }

        //分布式锁防止 缓存未加入布隆过滤器时 大量插入请求 访问MYSQL
        RLock lock = redissonClient.getLock(RedisConstant.LOCK_USER_REGISTER_KEY);

        try {
            //trylock防止阻塞等待，其他未获得锁的线程直接返回插入失败结果
            if(lock.tryLock()){
                 //检查插入是否成功
                 UserDO userDO = BeanUtil.toBean(userRegisterReqDTO, UserDO.class);
                 int insert = baseMapper.insert(userDO);
                 if(insert < 1){
                     throw new ClientException(UserErrorCodeEnun.USER_INSERT_FAILURE);
                 }
                 //用户数据入库，同时加入布隆过滤器，下次检测 只需检测布隆过滤器 无需访问mysql
                 rBloomFilter.add(userDO.getUsername());
                 return ;
             }
            throw new ClientException(UserErrorCodeEnun.USER_NOT_ACQUIRED_LOCK);
        } finally {
            lock.unlock();
        }
    }

    /**
     * 用户修改功能
     * @param userUpdateReqDTO
     * @return
     */
    @Override
    public void updateUser(UserUpdateReqDTO userUpdateReqDTO) {
        //TODO 判断请求用户是否为 对应用户username
        LambdaUpdateWrapper<UserDO> updateWrapper = Wrappers.lambdaUpdate(UserDO.class)
                .eq(UserDO::getUsername, userUpdateReqDTO.getUsername());
        baseMapper.update(BeanUtil.toBean(userUpdateReqDTO, UserDO.class),updateWrapper);

    }

    @Override
    public UserLoginRespDTO login(UserLoginReqDTO userLoginReqDTO) {
        //查询数据库中是否有对应用户信息
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, userLoginReqDTO.getUsername())
                .eq(UserDO::getPassword, userLoginReqDTO.getPassword())
                .eq(UserDO::getDelFlag, 0);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if(userDO == null ){
            throw new ClientException(UserErrorCodeEnun.USER_LOGIN_FAIL);
        }
        //登录成功生成token 加入redis缓存 并返回
        String token = UUID.randomUUID().toString();
        String key = RedisConstant.LOGIN_USER_KEY + userLoginReqDTO.getUsername();
        redisTemplate.opsForHash().put(key,token, JSON.toJSONString(userDO));
        redisTemplate.expire(key,30L, TimeUnit.DAYS);
        return new UserLoginRespDTO(token);
    }

    /**
     * 检测用户是否登录，是返回true
     * @param username
     * @param token
     * @return
     */
    @Override
    public Boolean checkLogin(String username, String token) {
        String key = RedisConstant.LOGIN_USER_KEY + username;
        return  redisTemplate.opsForHash().get(key, token) != null;
    }

    /**
     * 用户登出功能
     * @param username
     * @param token
     * @return
     */
    @Override
    public void logout(String username, String token) {
        String key = RedisConstant.LOGIN_USER_KEY + username;
        //1.查询用户是否已经登录
        Boolean login = checkLogin(username, token);
        if(login == Boolean.FALSE){
            throw new ClientException(UserErrorCodeEnun.USER_NOT_LOGIN );
        }
        //2.删除登录redis缓存即可
        redisTemplate.delete(key);
    }

}
